package com.wandian.net
{
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.utils.*;
	
	public class NetDispatcher extends EventDispatcher
	{
		private var bLogged:Boolean;
		private var fKey_str:String = "";
		private var bDebug:Boolean;
		private var loader:URLLoader;
		private var request:URLRequest;
		private var fRequestSended_bl:Boolean;
		private var fResponseReceived_bl:Boolean;
		private var vars:URLVariables;
		private var fRequestCommand_str:String;
		private var _loaderBalanceUpdate:URLLoader;
		private var gameDisp:GameDispatcher;
		private var sCreateSession:String;
		private var sDBLink:String;
		private var _requestBalanceUpdate:URLRequest;
		private var fResponse_urlv:URLVariables;
		private var responseParser:ResponseParser;
		private var sSessionID:String;
		public static const ACTION_PLACEBET:String = "PLACEBET";
		public static var PARAM_LAUNCH:String = "LAUNCH";
		public static var PARAM_DBLINK:String = "DBLINK";
		public static const EVENT_NET_ERROR_OCCURED:String = "onNetErrorOccured";
		public static var PARAM_NO:String = "NO";
		public static var RESULT_SESSIONERROR:String = "SESSIONERROR";
		public static const EVENT_NET_RESPONSE_RECEIVED:String = "onNetResponceReceived";
		public static var PARAM_COMMAND:String = "CMD";
		public static var PARAM_SID:String = "SID";
		public static var PARAM_CLIENT:String = "CLIENT";
		public static var PARAM_BET:String = "BET";
		public static var PARAM_FLASH:String = "FLASH";
		public static const ACTION_GETJACKPOT:String = "GETJACKPOT";
		public static var PARAM_CREATESESSION:String = "CREATESESSION";
		public static var PARAM_CHOICE:String = "CHOICE";
		public static var PARAM_KEY:String = "KEY";
		public static var PARAM_YES:String = "YES";
		public static const ACTION_ENTER:String = "ENTER";
		public static const ACTION_BONUS:String = "DOBONUS";
		public static var RESULT_OK:String = "OK";
		public static var PARAM_SESSIONID:String = "SESSIONID";
		
		public function NetDispatcher(param1:GameDispatcher)
		{
			fKey_str = "";
			this.updateState(false, false);
			this.gameDisp = param1;
			responseParser = new ResponseParser();
			if (CustomerSpecification.getInstance().readyToUse)
			{
				initParams();
			}
			else
			{
				CustomerSpecification.getInstance().addEventListener(CustomerSpecification.EVENT_UPDATED, this.initParams);
			}
			return;
		}// end function
		
		private function securityErrorHandler(event:SecurityErrorEvent) : void
		{
			return;
		}// end function
		
		private function completeHandlerBalanceUpdate(event:Event) : void
		{
			trace(">>>>>>>>>>>>>>>>>>>>>");
			trace("RESPONSE:\n" + this._loaderBalanceUpdate.data);
			trace("<<<<<<<<<<<<<<<<<<<<<");
			this.parseUpdateBalanceResponse(new URLVariables(this._loaderBalanceUpdate.data));
			return;
		}// end function
		
		private function decryptString(param1:String, param2:String) : String
		{
			var _loc_3:ByteArray = null;
			var _loc_4:ByteArray = null;
			var _loc_5:ICipher = null;
			_loc_3 = Hex.toArray(param2);
			_loc_4 = Hex.toArray(param1);
			_loc_5 = Crypto.getCipher("simple-des-ecb", _loc_3);
			_loc_5.decrypt(_loc_4);
			return Hex.toString(Hex.fromArray(_loc_4));
		}// end function
		
		protected function get requestProcessingInProgress() : Boolean
		{
			return this.requestSended && !this.responseReceived;
		}// end function
		
		protected function onResponseParsingError() : void
		{
			trace("NetDispatcher.onResponseParsingError() called");
			this.onErrorOccured();
			return;
		}// end function
		
		private function openHandler(event:Event) : void
		{
			return;
		}// end function
		
		public function setKey(param1:String) : void
		{
			if (param1 != null)
			{
				this.fKey_str = param1;
			}
			return;
		}// end function
		
		protected function onConnectionErrorOccured() : void
		{
			this.updateState(false, false);
			this.onErrorOccured();
			return;
		}// end function
		
		public function sendUpdateBalance() : void
		{
			var vars:URLVariables;
			trace("[NetDispatcher] sendUpdateBalance, url = " + Const.finsoftUpdateBalanceUrl);
			vars = new URLVariables();
			if (sSessionID)
			{
			}
			else
			{
				initParams();
			}
			vars["sessionId"] = sSessionID;
			vars["gameId"] = "BSG_BARBARYCOAST";
			this._requestBalanceUpdate = new URLRequest(Const.finsoftUpdateBalanceUrl);
			this._requestBalanceUpdate.method = URLRequestMethod.POST;
			this._requestBalanceUpdate.data = vars;
			this._loaderBalanceUpdate = new URLLoader();
			this.configureListenersBalanceUpdate(this._loaderBalanceUpdate);
			try
			{
				this._loaderBalanceUpdate.load(this._requestBalanceUpdate);
			}
			catch (error:Error)
			{
				trace("[NetDispatcher]: sendUpdateBalance => ERROR = " + error);
			}
			return;
		}// end function
		
		protected function get requestSended() : Boolean
		{
			return this.fRequestSended_bl;
		}// end function
		
		private function initParams(event:Event = null) : void
		{
			var _loc_2:LoaderInfo = null;
			var _loc_3:Object = null;
			if (event)
			{
				CustomerSpecification(event.target).removeEventListener(CustomerSpecification.EVENT_UPDATED, this.initParams);
			}
			_loc_2 = gameDisp.loaderInfo;
			_loc_3 = _loc_2.parameters;
			trace("NetDispatcher.initParams(): CUSTOMER ID = " + CustomerSpecification.getCustomerId());
			switch(CustomerSpecification.getCustomerId())
			{
				case CustomerSpecification.CUSTOMER_ID_TGC:
				case CustomerSpecification.CUSTOMER_ID_FINSOFT:
				{
					var _loc_4:* = gameDisp.SESSIONID;
					Const.SESSIONID = gameDisp.SESSIONID;
					sSessionID = _loc_4;
					var _loc_4:* = gameDisp.DBLINK;
					Const.DBLINK = gameDisp.DBLINK;
					sDBLink = _loc_4;
					break;
				}
				case CustomerSpecification.CUSTOMER_ID_GV:
				{
					sSessionID = Const.SESSIONID;
					sDBLink = Const.DBLINK;
					break;
				}
				default:
				{
					var _loc_4:* = _loc_3["SESSIONID"];
					Const.SESSIONID = _loc_3["SESSIONID"];
					sSessionID = _loc_4;
					if (_loc_3["SESSIONID"] == null)
					{
						var _loc_4:* = _loc_3["session"];
						Const.SESSIONID = _loc_3["session"];
						sSessionID = _loc_4;
					}
					var _loc_4:* = _loc_3["DBLINK"] ? (_loc_3["DBLINK"]) : ("DBLINK");
					Const.DBLINK = _loc_3["DBLINK"] ? (_loc_3["DBLINK"]) : ("DBLINK");
					sDBLink = _loc_4;
					break;
				}
			}
			var _loc_4:* = _loc_3["CREATESESSION"];
			Const.CREATESESSION = _loc_3["CREATESESSION"];
			sCreateSession = _loc_4;
			bLogged = Const.IS_LOGGED;
			bDebug = Const.IS_DEBUG;
			return;
		}// end function
		
		public function get requestCommand() : String
		{
			return this.fRequestCommand_str;
		}// end function
		
		private function ioErrorHandlerBalanceUpdate(event:IOErrorEvent) : void
		{
			trace("[NetDispatcher]:ioErrorHandlerBalanceUpdate => ioErrorHandler: " + event);
			gameDisp.showDialogSessionError();
			return;
		}// end function
		
		public function get response() : URLVariables
		{
			return this.fResponse_urlv;
		}// end function
		
		private function parseUpdateBalanceResponse(param1:URLVariables) : void
		{
			var _loc_2:String = null;
			_loc_2 = "";
			trace("[NetDispatcher]: parseUpdateBalanceResponse => rs.RESULT = " + param1.RESULT);
			if (param1.RESULT != null)
			{
				_loc_2 = param1.RESULT;
			}
			if (_loc_2 == "OK")
			{
				gameDisp.onUpdateBalanceReceived();
			}
			else
			{
				trace("[NetDispatcher]: parseUpdateBalanceResponse => RECIEVE ERROR from http://lobby.fs.discreetgaming.com/fsbalanceupdate");
				gameDisp.showDialogSessionError();
			}
			return;
		}// end function
		
		protected function get responseReceived() : Boolean
		{
			return this.fResponseReceived_bl;
		}// end function
		
		private function configureListenersBalanceUpdate(param1:IEventDispatcher) : void
		{
			param1.addEventListener(Event.COMPLETE, completeHandlerBalanceUpdate);
			param1.addEventListener(Event.OPEN, openHandler);
			param1.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			param1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			param1.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			param1.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandlerBalanceUpdate);
			return;
		}// end function
		
		private function httpStatusHandler(event:HTTPStatusEvent) : void
		{
			return;
		}// end function
		
		private function encryptString(param1:String, param2:String) : String
		{
			var _loc_3:ByteArray = null;
			var _loc_4:ByteArray = null;
			var _loc_5:ICipher = null;
			_loc_3 = Hex.toArray(param2);
			_loc_4 = Hex.toArray(Hex.fromString(param1));
			_loc_5 = Crypto.getCipher("simple-des-ecb", _loc_3);
			_loc_5.encrypt(_loc_4);
			return Hex.fromArray(_loc_4);
		}// end function
		
		protected function updateState(param1:Boolean, param2:Boolean) : void
		{
			this.fRequestSended_bl = param1;
			this.fResponseReceived_bl = param2;
			return;
		}// end function
		
		private function onResponseReceived(event:Event) : void
		{
			var lVars_urlv:URLVariables;
			var fDecodVars_str:String;
			var event:* = event;
			trace("[NetDispatcher] onResponseReceived, data = " + loader.data);
			this.updateState(true, true);
			this.fResponse_urlv = new URLVariables(loader.data);
			try
			{
				if (this.fKey_str != "" && Const.VALIDATING_HOST)
				{
					fDecodVars_str = this.decryptString(this.response["encrMess"], this.fKey_str);
					lVars_urlv = new URLVariables(fDecodVars_str);
					this.fResponse_urlv = lVars_urlv;
				}
				else
				{
					lVars_urlv = this.response;
				}
				responseParser.parseVars(vars[PARAM_COMMAND], lVars_urlv, gameDisp.onResponse, gameDisp.onErrorResponse, gameDisp.onErrorCodeResponse);
			}
			catch (aError_err:Error)
			{
				this.onResponseParsingError();
			}
			this.dispatchEvent(new Event(EVENT_NET_RESPONSE_RECEIVED));
			return;
		}// end function
		
		private function onSecurityErrorOccured(event:SecurityErrorEvent) : void
		{
			this.onConnectionErrorOccured();
			return;
		}// end function
		
		private function progressHandler(event:ProgressEvent) : void
		{
			return;
		}// end function
		
		private function onIOErrorOccured(event:IOErrorEvent) : void
		{
			this.onConnectionErrorOccured();
			return;
		}// end function
		
		protected function checkRequestCommand(param1:String) : void
		{
			if (param1 != ACTION_ENTER && param1 != ACTION_BONUS && param1 != ACTION_PLACEBET && param1 != ACTION_GETJACKPOT)
			{
				throw Error("Unsupported request command: " + param1);
			}
			return;
		}// end function
		
		public function sendRequest(param1:String, param2:URLVariables, param3:String) : void
		{
			var lServletUrl_str:String;
			var aRequestCommand_str:* = param1;
			var aVars_urlv:* = param2;
			var debugURL:* = param3;
			if (this.requestProcessingInProgress)
			{
				throw Error("Cannot send request due to previous request is in progress.");
			}
			this.initParams();
			this.checkRequestCommand(aRequestCommand_str);
			this.vars = aVars_urlv;
			var _loc_5:* = aRequestCommand_str;
			this.fRequestCommand_str = aRequestCommand_str;
			vars[PARAM_COMMAND] = _loc_5;
			vars[PARAM_CLIENT] = PARAM_FLASH;
			vars[PARAM_DBLINK] = sDBLink;
			switch(CustomerSpecification.getCustomerId())
			{
				case CustomerSpecification.CUSTOMER_ID_AP:
				case CustomerSpecification.CUSTOMER_ID_BS:
				case CustomerSpecification.CUSTOMER_ID_NYX:
				case CustomerSpecification.CUSTOMER_ID_AAMS:
				case CustomerSpecification.CUSTOMER_ID_BETKLASS:
				case CustomerSpecification.CUSTOMER_ID_RPK:
				case CustomerSpecification.CUSTOMER_ID_MRGREEN:
				{
					vars[PARAM_SID] = sSessionID;
					break;
				}
				case CustomerSpecification.CUSTOMER_ID_FINSOFT:
				{
					vars[PARAM_SID] = sSessionID;
					vars[PARAM_SESSIONID] = sSessionID;
					break;
				}
				default:
				{
					vars[PARAM_SESSIONID] = sSessionID;
					break;
				}
			}
			if (Const.IS_DEBUG)
			{
				lServletUrl_str = debugURL;
			}
			else
			{
				lServletUrl_str = Const.getServerURL(gameDisp.loaderInfo.url) + Const.SERVLET_NAME;
				switch(CustomerSpecification.getCustomerId())
				{
					case CustomerSpecification.CUSTOMER_ID_GB:
					case CustomerSpecification.CUSTOMER_ID_X18:
					case CustomerSpecification.CUSTOMER_ID_X18SB:
					{
						lServletUrl_str = lServletUrl_str + ";jsessionid=" + sSessionID;
						break;
					}
					case CustomerSpecification.CUSTOMER_ID_AP:
					case CustomerSpecification.CUSTOMER_ID_NYX:
					case CustomerSpecification.CUSTOMER_ID_AAMS:
					case CustomerSpecification.CUSTOMER_ID_BETKLASS:
					case CustomerSpecification.CUSTOMER_ID_RPK:
					case CustomerSpecification.CUSTOMER_ID_MRGREEN:
					{
						lServletUrl_str = Const.SERVLET_NAME;
						break;
					}
					case CustomerSpecification.CUSTOMER_ID_BS:
					{
						lServletUrl_str = Const.SERVLET_NAME;
						break;
					}
					case CustomerSpecification.CUSTOMER_ID_FINSOFT:
					{
						lServletUrl_str = GameData.getInstance().getFinsoftUrl();
						break;
					}
					default:
					{
						break;
						break;
					}
				}
			}
			request = new URLRequest(lServletUrl_str);
			request.data = new URLVariables(getEncryptMessage(vars));
			request.method = URLRequestMethod.POST;
			loader = new URLLoader();
			configureListeners(loader);
			try
			{
				this.updateState(true, false);
				loader.load(request);
			}
			catch (error:Error)
			{
				this.updateState(false, false);
				this.onConnectionErrorOccured();
			}
			return;
		}// end function
		
		protected function onErrorOccured() : void
		{
			this.dispatchEvent(new Event(EVENT_NET_ERROR_OCCURED));
			return;
		}// end function
		
		private function getEncryptMessage(param1:URLVariables) : String
		{
			var _loc_2:String = null;
			var _loc_3:String = null;
			var _loc_4:* = undefined;
			var _loc_5:String = null;
			_loc_2 = "";
			_loc_3 = "";
			for (_loc_4 in param1)
			{
				
				if (_loc_3 != "")
				{
					_loc_3 = _loc_3 + "&";
				}
				_loc_3 = _loc_3 + (_loc_4 + "=");
				_loc_3 = _loc_3 + param1[_loc_4];
			}
			_loc_2 = _loc_3;
			if (this.fKey_str != "" && Const.VALIDATING_HOST)
			{
				_loc_5 = this.encryptString(_loc_3, this.fKey_str);
				_loc_2 = "sid=" + sSessionID + "&encrMess=" + _loc_5 + "&gameId=" + Const.GAME_ID;
			}
			return _loc_2;
		}// end function
		
		private function configureListeners(param1:IEventDispatcher) : void
		{
			param1.addEventListener(Event.COMPLETE, this.onResponseReceived);
			param1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onSecurityErrorOccured);
			param1.addEventListener(IOErrorEvent.IO_ERROR, this.onIOErrorOccured);
			return;
		}// end function
		
	}
}
